﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using CNVP.Config;
using CNVP.Framework.Helper;
using CNVP.Framework.Utils;
using System.Text;
using System.IO;

namespace CNVP.JShop.Install
{
    public partial class Step3 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                TxtUserName.Text = UIConfig.SiteAdmin;
                TxtPerfix.Text = DBConfig.Prefix;
                TxtInstall.Text = UIConfig.InstallDir;
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            string _ServerName = TxtServerName.Text.Trim();
            string _DataBase = TxtDataBase.Text.Trim();
            string _SqlUserName = TxtSqlUserName.Text.Trim();
            string _SqlUserPass = TxtSqlUserPass.Text.Trim();
            string _AdminName = TxtUserName.Text.Trim();
            string _AdminPass=TxtUserPass.Text.Trim();
            string _Prefix = TxtPerfix.Text.Trim().ToUpper();
            string _InstallDir = TxtInstall.Text.Trim();
            string _DbConn = string.Format("server={0};uid={1};pwd={2};database={3};", _ServerName, _SqlUserName, _SqlUserPass, _DataBase);
            DbHelper.connectionString = _DbConn;
            if (!CheckConnection())
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('连接数据库失败,请检查您填写的数据库信息。');</script>");
            }
            else
            {
                Server.ScriptTimeout = 999999999;
                //保存配置文件
                BaseConfig.SaveXmlConfig("Prefix", _Prefix);
                BaseConfig.SaveXmlConfig("DBConn", _DbConn);
                BaseConfig.SaveXmlConfig("SiteAdmin", _AdminName);
                BaseConfig.SaveXmlConfig("InstallDir", _InstallDir);
                DBConfig.RefurbishCatch();
                UIConfig.RefurbishCatch();
                LicenseConfig.RefurbishCatch();
                //创建数据库脚本
                SetDateBaseInfo(_DbConn, _Prefix);
                //导入初始数据
                SetDefaultValue(_DbConn, _Prefix, _AdminName,_AdminPass);
                //安装操作成功，并删除安装程序
                FileUtils.DeleteFolder(Server.MapPath("~/Install"));
                FileUtils.DeleteFile(Server.MapPath("~/bin/CNVP.JShop.Install.dll"));
                MessageUtils.Write("<script language=\"javascript\" type=\"text/javascript\">alert('安装操作成功，确定后进入管理后台登陆页面！');window.location.href='"+ UIConfig.InstallDir+ UIConfig.AdminDir +"/Login.aspx';</script>");
            }
        }
        #region "检查账号密码是否正确"
        /// <summary>
        /// 检查数据库账号密码是否正确
        /// </summary>
        /// <returns></returns>
        private bool CheckConnection()
        {
            try
            {
                DbHelper.ExecuteNonQuery("SELECT 1");
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion
        #region "创建数据库表信息"
        private void SetDateBaseInfo(string DBConn,string Perfix)
        {
            using (SqlConnection Conn = new SqlConnection(DBConn))
            {
                Conn.Open();
                SqlCommand Command = Conn.CreateCommand();
                SqlTransaction _Transaction = Conn.BeginTransaction("CreateDateBase");
                Command.Connection = Conn;
                Command.Transaction = _Transaction;
                try
                {
                    DbHelper.connectionString = DBConn;
                    #region "删除已经存在的数据库表"
                    StringBuilder sb = new StringBuilder();
                    using (StreamReader objReader = new StreamReader(Server.MapPath("SqlServer/Setup1.sql"), Encoding.UTF8))
                    {
                        sb.Append(objReader.ReadToEnd());
                        objReader.Close();
                    }
                    if (Perfix.ToUpper() == "CNVP_")
                    {
                        DbHelper.ExecuteNonQuery(sb.ToString());
                    }
                    else
                    {
                        DbHelper.ExecuteNonQuery(sb.ToString().Replace("CNVP_", Perfix));
                    }
                    #endregion
                    #region "创建数据库表"
                    StringBuilder sbCreate = new StringBuilder();
                    using (StreamReader objReader = new StreamReader(Server.MapPath("SqlServer/Setup2.sql"), Encoding.UTF8))
                    {
                        sbCreate.Append(objReader.ReadToEnd());
                        objReader.Close();
                    }

                    if (Perfix.ToUpper() == "CNVP_")
                    {
                        DbHelper.ExecuteCommandWithSplitter(sbCreate.ToString());
                    }
                    else
                    {
                        DbHelper.ExecuteCommandWithSplitter(sbCreate.ToString().Replace("CNVP_", Perfix));
                    }
                    #endregion
                    #region "插入数据"
                    StringBuilder sbInsert = new StringBuilder();
                    using (StreamReader objReader = new StreamReader(Server.MapPath("SqlServer/Setup3.sql"), Encoding.UTF8))
                    {
                        sbInsert.Append(objReader.ReadToEnd());
                        objReader.Close();
                    }
                    if (Perfix.ToUpper() == "CNVP_")
                    {
                        DbHelper.ExecuteCommandWithSplitter(sbInsert.ToString());
                    }
                    else
                    {
                        DbHelper.ExecuteCommandWithSplitter(sbInsert.ToString().Replace("CNVP_", Perfix));
                    }
                    #endregion
                    #region "插入数据区域"
                    StringBuilder sbInsertArea = new StringBuilder();
                    using (StreamReader objReader = new StreamReader(Server.MapPath("SqlServer/Setup4.sql"), Encoding.UTF8))
                    {
                        sbInsertArea.Append(objReader.ReadToEnd());
                        objReader.Close();
                    }
                    if (Perfix.ToUpper() == "CNVP_")
                    {
                        DbHelper.ExecuteCommandWithSplitter(sbInsertArea.ToString());
                    }
                    else
                    {
                        DbHelper.ExecuteCommandWithSplitter(sbInsertArea.ToString().Replace("CNVP_", Perfix));
                    }
                    #endregion
                    #region "插入数据其他"
                    StringBuilder sbInsertOther = new StringBuilder();
                    using (StreamReader objReader = new StreamReader(Server.MapPath("SqlServer/Setup5.sql"), Encoding.UTF8))
                    {
                        sbInsertOther.Append(objReader.ReadToEnd());
                        objReader.Close();
                    }
                    if (Perfix.ToUpper() == "CNVP_")
                    {
                        DbHelper.ExecuteCommandWithSplitter(sbInsertOther.ToString());
                    }
                    else
                    {
                        DbHelper.ExecuteCommandWithSplitter(sbInsertOther.ToString().Replace("CNVP_", Perfix));
                    }
                    #endregion
                    _Transaction.Commit();
                }
                catch
                {
                    _Transaction.Rollback();
                }
            }
        }
        #endregion
        #region "导入初始数据"
        private void SetDefaultValue(string DbConn, string Perfix,string AdminName,string AdminPass)
        {
            using (SqlConnection Conn = new SqlConnection(DbConn))
            {
                Conn.Open();
                SqlCommand Command = Conn.CreateCommand();
                SqlTransaction _Transaction = Conn.BeginTransaction("InsertDataBase");
                Command.Connection = Conn;
                Command.Transaction = _Transaction;
                DbHelper.connectionString = DbConn;
                try
                {
                    
                    //创建管理员账号
                    string StrSql = string.Format("Insert Into " + Perfix + "Admin (AdminName, AdminPass, LoginNum, IsLock, RoleID) Values ('{0}','{1}',0,0,1)", AdminName, EncryptUtils.MD5(AdminPass));
                    DbHelper.ExecuteNonQuery(StrSql);

                    _Transaction.Commit();
                }
                catch
                {
                    _Transaction.Rollback();
                }
            }
        }
        #endregion
    }
}
